﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Web;
using log4net;

namespace Matrix.Common.Utility
{
    /// <summary>
    /// 文件操作类
    /// </summary>
    public static class FileHelper
    {
        private static ILog _fileLog = LogManager.GetLogger(typeof(FileHelper));
        #region 1.0 创建 新文件名 +string NewFileName(string strOldFileName)
        /// <summary>
        /// 创建 新文件名
        /// </summary>
        /// <returns></returns>
        public static string NewFileName(string strOldFileName)
        {
            return Guid.NewGuid().ToString() ;//+ Path.GetExtension(strOldFileName);
        }
        #endregion

        #region 2.0 获取图片对应 缩略图 名称 +string GetThumbName(string strImgName)
        /// <summary>
        /// 获取图片对应 缩略图 名称
        /// </summary>
        /// <param name="strImgName"></param>
        /// <returns></returns>
        public static string GetThumbName(string strImgName, string type)
        {
            //1.jpg -> 1_thumb.jpg
            return strImgName.Replace(".", "_" + type + ".");
        }
        #endregion

        #region 2.1根据缩略图 获取原图 名称 +string GetOriginalName(string strImgName)
        /// <summary>
        /// 根据缩略图 获取原图 名称
        /// </summary>
        /// <param name="strImgName"></param>
        /// <returns></returns>
        public static string GetOriginalName(string strThunmbImgName)
        {
            //1_thumb.jpg -> 1.jpg
            return strThunmbImgName.Replace("_thumb.", ".");
        }
        #endregion
        #region 获取文件的后缀名（.png）
        /// <summary>
        /// 获取文件的后缀名（.png）
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string GetFileHZ(string filePath)
        {
            if (filePath.Length > 0)
                return filePath.Substring(filePath.LastIndexOf("."), filePath.Length - filePath.LastIndexOf("."));
            else
                return filePath;
        }
        #endregion
        #region 3.0 保存图片 并 生成缩略图 +SaveImgAndThumb(System.Web.HttpPostedFile file, string strImgName, string savePath)
        /// <summary>
        /// 3.0 保存图片 并 生成缩略图
        /// </summary>
        /// <param name="file">图片文件对象</param>
        /// <param name="strImgName">图片名</param>
        /// <param name="savePath">保存的文件夹路径</param>
        public static string SaveImgAndThumb(System.Web.HttpPostedFileBase file, string strImgName, string savePath, float fThumbWidth, float fThumbHeight)
        {     
            string fileNameExt = GetFileHZ(file.FileName);
            string imgURl;
            //3.1获取原图文件流
            using (Image img = Image.FromStream(file.InputStream))
            {
                imgURl = savePath  + strImgName + fileNameExt;
                //3.1.1保存原图
                img.Save(imgURl);
            }
            string fileQZ = "_b";
      
           // CutPic(uploadPath + fileName + fileNameExt, uploadPath + fileName + fileQZ + fileNameExt, Convert.ToInt32(bigWidth), 0, "W");
            CutPic(imgURl, savePath + strImgName + fileQZ + fileNameExt, int.Parse(fThumbWidth.ToString(CultureInfo.InvariantCulture)), int.Parse(fThumbHeight.ToString(CultureInfo.InvariantCulture)), "W");
            //RotateImg(imgURl, 270, savePath + strImgName +"_c" + fileNameExt);
            //File.Delete(
            //3.2保存 缩略图
          //  MakeThumbImg(file, strImgName, savePath, fThumbWidth, fThumbHeight, "b");
            return imgURl;
        }
        #endregion

        #region 4.0 生成缩略图 +void MakeThumbImg(HttpPostedFile file, string strFileName, string savePath, float fThumbWidth, float fThumbHeight)
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="file">文件对象</param>
        /// <param name="strFileName">不带后缀的文件名</param>
        /// <param name="savePath">文件夹路径</param>
        /// <param name="intThumbWidth">缩略图宽</param>
        /// <param name="intThumbHeight">缩略图高</param>
        public static string MakeThumbImg(System.Web.HttpPostedFileBase file, string strFileName, string savePath, float fThumbWidth, float fThumbHeight, string type)
        {
            //将文件流 转成 图片
            using (Image img = Image.FromStream(file.InputStream))
            {
                #region 计算 缩略图的 宽高
                float imgW = img.Width;//原图 宽
                float imgH = img.Height;//原图 高
                //根据 原图的 高宽比，算出 缩略图的 高（保证缩略图不变形）
                float thumbWidth;
                float thumbHeight;
                //获取第一张绘制图的大小,(比较 原图的宽/缩略图的宽 和 原图的高/缩略图的高) 
                thumbWidth = imgW;
                thumbHeight = imgH;
                //宽大于高或宽等于高（横向矩形或正方）
                if (imgW > imgH || imgW == imgH)
                {
                    //如果宽大于 缩略图 原定的宽度
                    if (imgW > fThumbWidth)
                    {
                        //宽按缩略图宽，高按比例缩放
                        thumbWidth = fThumbWidth;//将 原定的 缩略图宽度 设置为 图片要缩小的宽度
                        thumbHeight = imgH * (fThumbWidth / imgW);
                    }
                }
                //高大于宽（竖图）
                else
                {
                    //如果高大于模版
                    if (imgH > fThumbHeight)
                    {
                        //高按模版，宽按比例缩放
                        thumbHeight = fThumbHeight;
                        thumbWidth = imgW * (fThumbHeight / imgH);
                    }
                }
                #endregion

                //按照高宽比算出的宽和高来生成缩略图，并保存 
                using (Image imgThumb = new Bitmap((int)thumbWidth, (int)thumbHeight))
                {
                    //创建“画家”对象，并告知在imgThumb上“作画”
                    using (Graphics g = Graphics.FromImage(imgThumb))
                    {
                        //设置缩略图的背景色为透明
                        g.Clear(Color.Transparent);
                        //设置一系列图片质量
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        //将大图 画到 小图上
                        g.DrawImage(img, new Rectangle(0, 0, imgThumb.Width, imgThumb.Height), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
                    }
                    //保存缩略图
                    string newImg = GetThumbName(savePath + "/" + strFileName, type);

                    _fileLog.Error("UserController | UploadHeadImage | newImg " + newImg);
                    imgThumb.Save(newImg);
                    return newImg;
                }
            }
        }



        #endregion


        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>    
        public static void CutPic(string originalImagePath, string thumbnailPath, int width, int height, string mode = "Cut")
        {
            int i_Width = 0, i_Height = 0;
            //string strPicPath = HttpContext.Current.Server.MapPath(originalImagePath);
            string strPicPath = originalImagePath;
            System.Drawing.Image uImage = System.Drawing.Image.FromFile(strPicPath);
            i_Width = uImage.Width < width ? uImage.Width : width;
            i_Height = uImage.Height < height ? uImage.Height : height;
            uImage.Dispose();

            width = i_Width;
            height = i_Height;

            //originalImagePath = HttpContext.Current.Server.MapPath(originalImagePath);
            //thumbnailPath = HttpContext.Current.Server.MapPath(thumbnailPath);
            originalImagePath = originalImagePath;
            thumbnailPath = thumbnailPath;
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                
                    break;
                case "W"://指定宽，高按比例
                    if (originalImage.Width < width)
                    {
                        towidth = originalImage.Width;
                        toheight = originalImage.Height;
                    }
                    else
                    {
                        toheight = originalImage.Height * width / originalImage.Width;
                    }
                    break;
                case "H"://指定高，宽按比例
                    if (originalImage.Height < height)
                    {
                        toheight = originalImage.Height;
                        towidth = originalImage.Width;
                    }
                    else
                    {
                        towidth = originalImage.Width * height / originalImage.Height;
                    }
                    break;
                case "Cut"://指定高宽裁减（不变形）                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                new System.Drawing.Rectangle(x, y, ow, oh),
                System.Drawing.GraphicsUnit.Pixel);

            try
            {
                string Path =thumbnailPath.Substring(0, thumbnailPath.LastIndexOf('\\'));
                if (!Directory.Exists(Path))
                {
                    Directory.CreateDirectory(Path);
                }

                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }


        #region 图片旋转
        public static Image RotateImg(string filename, int angle, string targetFileName)
        {

            return RotateImg(GetSourceImg(filename), angle, targetFileName);

        }
        public static Image GetSourceImg(string filename)
        {

            Image img;



            img = Bitmap.FromFile(filename);


            return img;

        }
        /// <summary>    

        /// 以逆时针为方向对图像进行旋转    

        /// </summary>    

        /// <param name="b">位图流</param>    

        /// <param name="angle">旋转角度[0,360](前台给的)</param>    

        /// <returns></returns>    

        public static Image RotateImg(Image b, int angle, string targetFileName)
        {

            angle = angle % 360;


            //弧度转换    

            double radian = angle * Math.PI / 180.0;

            double cos = Math.Cos(radian);

            double sin = Math.Sin(radian);


            //原图的宽和高    

            int w = b.Width;

            int h = b.Height;

            int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)));

            int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)));


            //目标位图    

            Bitmap dsImage = new Bitmap(W, H);

            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(dsImage);

            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;

            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;


            //计算偏移量    

            Point Offset = new Point((W - w) / 2, (H - h) / 2);


            //构造图像显示区域：让图像的中心与窗口的中心点一致    

            Rectangle rect = new Rectangle(Offset.X, Offset.Y, w, h);

            Point center = new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);


            g.TranslateTransform(center.X, center.Y);

            g.RotateTransform(360 - angle);


            //恢复图像在水平和垂直方向的平移    

            g.TranslateTransform(-center.X, -center.Y);

            g.DrawImage(b, rect);


            //重至绘图的所有变换    

            g.ResetTransform();


            g.Save();

            g.Dispose();

            //保存旋转后的图片    

            b.Dispose();

            dsImage.Save(targetFileName, System.Drawing.Imaging.ImageFormat.Jpeg);

            return dsImage;

        }   
        #endregion
    }
}
